package com.niiwoo.civet.trade.service.local.statisticsinfo;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.base.enums.DeadlineUnitEnum;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestOrder;
import com.niiwoo.civet.trade.dao.mapper.ProjectInvestOrderMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;
import com.niiwoo.civet.trade.dto.request.thirdplateformdata.WangDaiZhiJiaRequestDTO;
import com.niiwoo.civet.trade.dto.response.thirdplateformdata.WangDaiZhiJiaOverDebtResponseDTO;
import com.niiwoo.civet.trade.dto.response.thirdplateformdata.WangDaiZhiJiaProjectResponseDTO;
import com.niiwoo.civet.trade.enums.*;
import com.niiwoo.tripod.base.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by bincun on 2018/8/31.
 * 网贷之家
 */
@Service
@Slf4j
public class WangdaizhijiaLocalService {

    @Autowired
    private ProjectMapperExt projectMapperExt;
    @Autowired
    private ProjectInvestOrderMapperExt projectInvestOrderMapperExt;
    @Value("${h5-niiwoo-project-detail-url}")
    private String h5BorrowDetailUrl;

    public WangDaiZhiJiaProjectResponseDTO getProjectsByDate(WangDaiZhiJiaRequestDTO dto){
        log.info("网贷之前统计标的信息，dto={}",JSON.toJSONString(dto));
        WangDaiZhiJiaProjectResponseDTO responseDTO = new WangDaiZhiJiaProjectResponseDTO();
        int start = 0;
        if (dto.getCurrentPage() > 1){
             start  = dto.getPageSize() * (dto.getCurrentPage()-1);
        }
        //总条数
        Long countNumLong = (Long) projectMapperExt.countFullProjectByDate(new DateTime(dto.getDate()).toDate(),new DateTime(dto.getDate()).plusDays(1).toDate()).get("countNum");
        Integer countNum = countNumLong.intValue();

        List<Project> projectList = projectMapperExt.selectFullProjectByDate(new DateTime(dto.getDate()).toDate(),new DateTime(dto.getDate()).plusDays(1).toDate(),start,dto.getPageSize());
        BigDecimal totalAmountBigDecimal = (BigDecimal) projectMapperExt.countFullProjectByDate(new DateTime(dto.getDate()).toDate(),new DateTime(dto.getDate()).plusDays(1).toDate()).get("contractAmountTotal");
        Double totalAmount = totalAmountBigDecimal.setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
        List<WangDaiZhiJiaProjectResponseDTO.ProjectInfo> projectInfoList = new ArrayList<>();
        for (Project project : projectList) {
            WangDaiZhiJiaProjectResponseDTO.ProjectInfo projectInfo = new WangDaiZhiJiaProjectResponseDTO.ProjectInfo();
            projectInfo.setAmount(project.getContractAmount().setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
            //totalAmount = totalAmount + projectInfo.getAmount();
            projectInfo.setAmountUsedDesc(project.getTitle());
            projectInfo.setCity(project.getLoanCity());
            projectInfo.setDeadline(project.getDeadline());
            projectInfo.setDeadlineUnit(DeadlineUnitEnum.BY_DAY.getDeadlineUnit().equals(project.getDeadlineUnit())? "天":"月");
            projectInfo.setGuarantorsType(null);
            projectInfo.setInterestRate(project.getBorrowRate().multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP).toString()+"%");
            projectInfo.setIsAgency(BorrowerTypeEnum.COMPANY.getType().equals(project.getBorrowerType())? 1:0);
            projectInfo.setLoanUrl(h5BorrowDetailUrl+project.getProjectId());
            projectInfo.setPlateType(null);
            projectInfo.setProjectId(project.getProjectId().toString());
            projectInfo.setProvince(project.getLoanProvince().replace("省",""));
            projectInfo.setPublishTime(DateUtils.format(project.getPublishTime(),DateUtils.SHOW_DATETIME_FORMAT));
            //1, "到期还本付息"    2, "等额本息"
            projectInfo.setRepaymentType(project.getRepaymentType().equals(RepaymentTypeEnum.MONTHLY_INTEREST_PAYMENT_DUE.getValue())? 9 : project.getRepaymentType().intValue());
            projectInfo.setRevenue(project.getManageFee().add(project.getGuaranteeFee().add(project.getConsultingFee())).toString());
            projectInfo.setReward(Double.valueOf("0"));
            projectInfo.setSchedule("100");
            projectInfo.setSuccessTime(DateUtils.format(project.getFullSuccessTime(),DateUtils.SHOW_DATETIME_FORMAT));
            projectInfo.setTitle(project.getTitle());
            projectInfo.setType(LoanTypeEnum.enumOf(project.getLoanType()).getDesc());
            projectInfo.setUserName(project.getBorrowUserId());
            projectInfo.setUserAvatarUrl(project.getBorrowHeadImage());
            List<WangDaiZhiJiaProjectResponseDTO.ProjectInfo.InvestorOrder> investorOrderList = new ArrayList<>();
            projectInfo.setSubscribes(investorOrderList);

            List<ProjectInvestOrder> projectInvestOrderList = projectInvestOrderMapperExt.selectInvestedList(project.getProjectId());
            for (ProjectInvestOrder order : projectInvestOrderList) {
                if (order.getEvolutionStatus().equals(ProjectInvestOrderEvolutionStatusEnum.CLOSED.getValue())
                        || order.getEvolutionStatus().equals(ProjectInvestOrderEvolutionStatusEnum.TRANSFERRED.getValue())){
                    log.debug("投资订单已关闭或者已转让orderId={}",order.getId());
                    continue;
                }
                WangDaiZhiJiaProjectResponseDTO.ProjectInfo.InvestorOrder investorOrder = new WangDaiZhiJiaProjectResponseDTO.ProjectInfo.InvestorOrder();
                investorOrder.setAddDate(DateUtils.format(order.getCreateTime(),DateUtils.SHOW_DATETIME_FORMAT));
                //2表示债转标，取债权份额
                investorOrder.setAmount(order.getInvestType().equals(Byte.valueOf("2"))? order.getShare().doubleValue():order.getAmount().doubleValue());
                investorOrder.setValidAmount(investorOrder.getAmount());//与amount一致
                investorOrder.setSourceType(null);
                investorOrder.setStatus(1);
                investorOrder.setSubscribeUserName(order.getUserId());
                investorOrder.setType(InvestWayEnum.AUTO.getValue().equals(order.getType())? 1:0);
                investorOrderList.add(investorOrder);
            }
            projectInfoList.add(projectInfo);
        }
        log.debug("标的列表详细信息={}", JSON.toJSONString(projectInfoList));
        responseDTO.setBorrowList(projectInfoList);
        responseDTO.setCurrentPage(dto.getCurrentPage());
        responseDTO.setTotalAmount(totalAmount);
        responseDTO.setTotalCount(countNum);
        responseDTO.setTotalPage(countNum % dto.getPageSize() == 0 ?countNum/dto.getPageSize() : countNum/dto.getPageSize()+1);
        log.info("网贷之前统计结果,currentPage={},totalAmount={},totalCount={},totalPage={}",responseDTO.getCurrentPage(),responseDTO.getTotalAmount(),responseDTO.getTotalCount(),responseDTO.getTotalPage());
        return responseDTO;
    }

    public WangDaiZhiJiaOverDebtResponseDTO getOverdebtProjects(WangDaiZhiJiaRequestDTO dto){
        WangDaiZhiJiaOverDebtResponseDTO responseDTO = new WangDaiZhiJiaOverDebtResponseDTO();
        int start = 0;
        if (dto.getCurrentPage() > 1){
            start  = dto.getPageSize() * (dto.getCurrentPage()-1);
        }
        Date endTime  = new DateTime(dto.getDate()).plusDays(1).toDate();

        int countNum = projectMapperExt.countOverdebtProjects(dto.getDate(),endTime);
        List<ProjectForTianyan> projectList = projectMapperExt.selectOverdebtProjects(dto.getDate(),endTime,start,dto.getPageSize());
        List<WangDaiZhiJiaOverDebtResponseDTO.OverDebtProject> overDebtProjectList = new ArrayList<>();
        for (Project project : projectList) {
            WangDaiZhiJiaOverDebtResponseDTO.OverDebtProject overDebtProject = new WangDaiZhiJiaOverDebtResponseDTO.OverDebtProject();
            overDebtProject.setDeadline(project.getDeadline());
            overDebtProject.setDeadlineUnit(DeadlineUnitEnum.BY_DAY.getDeadlineUnit().equals(project.getDeadlineUnit())? "天":"月");
            overDebtProject.setProjectId(project.getProjectId().toString());
            overDebtProjectList.add(overDebtProject);
        }
        responseDTO.setCurrentPage(dto.getCurrentPage());
        responseDTO.setTotalPage(countNum % dto.getPageSize() == 0 ?countNum/dto.getPageSize() : countNum/dto.getPageSize()+1);
        responseDTO.setPreapys(overDebtProjectList);
        return responseDTO;
    }
}
